package com.taijihuabao.common.activititasklistener.expensetasklistener;

import com.taijihuabao.modules.entity.DeptUserEntity;
import com.taijihuabao.modules.entity.ExpenseEntity;
import com.taijihuabao.modules.mapper.DeptMapper;
import com.taijihuabao.modules.mapper.DeptUserMapper;
import com.taijihuabao.modules.mapper.ExpenseMapper;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @title: parentDeptListener
 * @Author luoxianan
 * @Date: 2021/12/9 14:26
 * @Version 1.0
 */
@Component
public class ParentDeptListener implements TaskListener {

    /**
     * 主管
     */
    private final String ADMINISTRATOR = "administrator";
    /**
     * 审核员
     */
    private final String ASSESSOR = "assessor";
    private final String TEXT = "父级部门审批";
    private final String TYPE= "create";
    @Resource
    private ExpenseMapper expenseMapper;
    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private DeptMapper deptMapper;
    @Override
    public void notify(DelegateTask delegateTask) {
        if (delegateTask.getName().equals(TEXT) && TYPE.equals(delegateTask.getEventName())) {
            //获取审批单id
            String bussinessKey = delegateTask.getExecution().getProcessInstanceBusinessKey();
            ExpenseEntity expenseEntity = expenseMapper.selectById(Long.valueOf(bussinessKey));
            //查询部门所有人
            List<DeptUserEntity> applys = deptUserMapper.selectDeptByUserId(expenseEntity.getApplyUserId());
            String dept = applys.get(0).getDeptCode();
            String parentDept = deptMapper.selectDeptByCode(dept).getParentDept();
            List<DeptUserEntity> users = deptUserMapper.selectDeptByDeptCode(parentDept);
            //根据部门和id查询角色
            for (DeptUserEntity due : users) {
                if (ADMINISTRATOR.equals(due.getDeptRole()) || ASSESSOR.equals(due.getDeptRole())) {
                    delegateTask.addCandidateUser(String.valueOf(due.getUserId()));
                }
            }
        }
    }
}
